<template>
  <div class="main-content">
    <!-- 列表页 -->
    <div v-if="showFlag">
      <el-form :inline="true" :model="searchForm" class="form-content">
        <el-row :gutter="20" class="slt"
                :style="{justifyContent:'center'}">
          <el-form-item label='学号'>
            <el-input v-model="searchForm.studentaccount" placeholder="学号"
                      clearable></el-input>
          </el-form-item>
          <el-form-item label='学生姓名'>
            <el-input v-model="searchForm.studentname" placeholder="学生姓名"
                      clearable></el-input>
          </el-form-item>
          <el-form-item label='性别'>

            <el-input v-model="searchForm.gender" placeholder="性别"
                      clearable></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="success" @click="search()">
              {{'查询'}}
            </el-button>
          </el-form-item>
        </el-row>
        <el-row class="ad"
                :style="{justifyContent: 'flex-start'}">
          <el-form-item>
            <!-- 按钮组 -->
            <el-button-group style="margin-right: 10px">
              <!-- 新增按钮 -->
              <el-button
                  style="
                  background-color: #3891d7;color: #eeeeee"
                  @click="addOrUpdateHandler()"
              >
                {{'新增'}}
              </el-button>

              <!-- 删除按钮 -->
              <el-button
                  style="
                  background-color: #3891d7;color: #eeeeee"
                  :disabled="dataListSelections.length <= 0"

                  @click="deleteHandler()"
              >
                {{'删除'}}
              </el-button>

              <!-- 上传按钮，作为上传触发器 -->
            </el-button-group>

            <el-upload
                class="upload-demo"
                action=""
                :on-preview="handlePreview"
                :on-remove="handleRemove"
                :before-remove="beforeRemove"
                :limit="1"
                :on-exceed="handleExceed"
                :file-list="fileList"
                list-type="text"
                accept=".xls,.xlsx,.csv"
                :http-request="customHttpRequest"
                style="display: inline-flex; align-items: center;"
            ><!-- 设置为文本模式，防止文件列表出现独占整行的布局 -->
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
            <!-- 按钮组结束 -->
          </el-form-item>
        </el-row>

      </el-form>
      <div class="table-content">
        <el-table class="tables" :size="contents.tableSize" :show-header="contents.tableShowHeader"
                  :header-row-style="headerRowStyle" :header-cell-style="headerCellStyle"
                  :border="contents.tableBorder"
                  :fit="contents.tableFit"
                  :stripe="contents.tableStripe"
                  :row-style="rowStyle"
                  :cell-style="cellStyle"
                  :style="{width: '100%',fontSize:contents.tableContentFontSize,color:contents.tableContentFontColor}"
                  :data="dataList"
                  v-loading="dataListLoading"
                  @selection-change="selectionChangeHandler">
          <el-table-column v-if="contents.tableSelection"
                           type="selection"
                           header-align="center"
                           align="center"
                           width="50">
          </el-table-column>

          <el-table-column label="索引" v-if="contents.tableIndex" type="index" width="50"/>
          <el-table-column :sortable="contents.tableSortable" :align="contents.tableAlign"
                           prop="studentaccount"
                           header-align="center"
                           label="学号">
            <template v-slot:="scope">
              {{ scope.row.studentaccount }}
            </template>
          </el-table-column>
          <el-table-column :sortable="contents.tableSortable" :align="contents.tableAlign"
                           prop="studentname"
                           header-align="center"
                           label="学生姓名">
            <template v-slot="scope">
              {{ scope.row.studentname }}
            </template>
          </el-table-column>
          <el-table-column :sortable="contents.tableSortable" :align="contents.tableAlign"
                           prop="studentclass"
                           header-align="center"
                           label="学生班级">
            <template v-slot="scope">
              {{ scope.row.studentclass }}
            </template>
          </el-table-column>
          <el-table-column :sortable="contents.tableSortable" :align="contents.tableAlign"
                           prop="studentcollege"
                           header-align="center"
                           label="学生学院">
            <template v-slot="scope">
              {{ scope.row.studentcollege }}
            </template>
          </el-table-column>
          <el-table-column :sortable="contents.tableSortable" :align="contents.tableAlign"
                           prop="gender"
                           header-align="center"
                           label="性别">
            <template v-slot="scope">
              {{ scope.row.gender }}
            </template>
          </el-table-column>

          <el-table-column width="300" :align="contents.tableAlign"
                           header-align="center"
                           label="操作">
            <template v-slot="scope">
              <el-button
                  type="success"  size="mini" @click="addOrUpdateHandler(scope.row.id,'info')">
                {{'详情'}}
              </el-button>
              <!--              -->

              <el-button
                  type="primary"  size="mini" @click="addOrUpdateHandler(scope.row.id)">
                {{'修改'}}
              </el-button>
              <!--              -->

              <el-button
                  type="danger" size="mini" @click="deleteHandler(scope.row.id)">
                {{'删除'}}
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
            clsss="pages"
            :layout="layouts"
            @size-change="sizeChangeHandle"
            @current-change="currentChangeHandle"
            :current-page="pageIndex"
            :page-sizes="[10, 20, 50, 100]"
            :page-size="Number(contents.pageEachNum)"
            :total="totalPage"
            :small="contents.pageStyle"
            class="pagination-content"
            :background="contents.pageBtnBG"
            :style="{textAlign:contents.pagePosition==1?'left':contents.pagePosition==2?'center':'right'}"
        ></el-pagination>
      </div>
    </div>
    <!-- 添加/修改页面  将父组件的search方法传递给子组件-->
    <add-or-update v-if="addOrUpdateFlag" :parent="this" ref="addOrUpdate"></add-or-update>


  </div>
</template>
<script>
import AddOrUpdate from "./add-or-update";
export default {
  data() {
    return {
      searchForm: {
        key: ""
      },
      form: {},
      dataList: [],
      pageIndex: 1,
      pageSize: 10,
      totalPage: 0,
      dataListLoading: false,
      dataListSelections: [],
      showFlag: true,
      sfshVisiable: false,
      shForm: {},
      chartVisiable: false,
      addOrUpdateFlag: false,
      fileList: [],
      contents: {
        "searchBtnFontColor": "rgba(49,47,47,0.88)",
        "pagePosition": "1",
        "inputFontSize": "14px",
        "inputBorderRadius": "5px",
        "tableBtnDelFontColor": "#333",
        "searchBtnHeight": "40px",
        "inputIconColor": "#C0C4CC",
        "searchBtnBorderRadius": "5px",
        "tableStripe": false,
        "tableBtnDelBgColor": "rgba(214, 186, 232, 1)",
        "tableSize": "medium",
        "searchBtnBorderStyle": "solid",
        "tableSelection": true,
        "searchBtnBorderWidth": "1px",
        "tableContentFontSize": "14px",
        "searchBtnBgColor": "rgba(218,229,223,0.66)",
        "inputTitleSize": "16px",
        "pageJumper": true,
        "tableBtnDetailFontColor": "#333",
        "tableBtnHeight": "40px",
        "pagePager": true,
        "searchBtnBorderColor": "#DCDFE6",
        "tableHeaderFontColor": "rgba(47,44,44,0.76)",// 列首字体颜色
        "tableBtnBorderRadius": "5px",

        "btnAdAllDelFontColor": "#333",
        "btnAdAllWarnFontColor": "#ffffff",// 字体颜色
        "btnAdAllBorderColor": "#b2ac68",// 左上按钮边框颜色
        "btnAdAllHeight": "40px",
        "btnAdAllWarnBgColor": "rgba(75,222,146,0.8)",
        "btnAdAllFontWeight": 550,
        "btnAdAllBorderWidth": "1px",
        "btnAdAllAddBgColor": "rgba(75,222,146,0.8)",//背景颜色

        "tableStripeFontColor": "#606266",
        "tableBtnBorderStyle": "solid",
        "inputHeight": "40px",
        "btnAdAllBorderRadius": "5px",
        "btnAdAllDelBgColor": "rgba(255, 76, 10, 0.71)",
        "pagePrevNext": true,
        "searchBtnFont": "1",
        "tableIndex": true,
        "btnAdAllIcon": "1",
        "tableSortable": true,
        "pageSizes": true,
        "tableFit": true,
        "pageBtnBG": true,
        "searchBtnFontSize": "14px",
        "tableBtnEditBgColor": "rgba(202, 235, 202, 1)",
        "inputBorderWidth": "1px",
        "inputFontPosition": "2",
        "inputFontColor": "#333",
        "pageEachNum": 10,
        "tableHeaderBgColor": "rgb(255,255,255)",//列首背景
        "inputTitleColor": "rgba(54,55,58,0.88)",
        "btnAdAllBoxPosition": "1",
        "tableBtnDetailBgColor": "rgba(173, 241, 242, 1)",
        "inputIcon": "0",
        "searchBtnIconPosition": "1",
        "btnAdAllFontSize": "14px",
        "inputBorderStyle": "solid",
        "inputBgColor": "rgba(255,255,255,0.66)",
        "pageStyle": false,
        "pageTotal": true,
        "btnAdAllAddFontColor": "#333",
        "tableBtnFont": "1",
        "tableContentFontColor": "#29292f",//表格内字体
        "inputBorderColor": "#DCDFE6",
        "tableShowHeader": true,
        "tableBtnFontSize": "14px",
        "tableBtnBorderColor": "#DCDFE6",
        "inputIconPosition": "1",
        "tableBorder": true,
        "btnAdAllBorderStyle": "solid",
        "tableBtnBorderWidth": "1px",
        "tableStripeBgColor": "#F5F7FA",
        "tableBtnEditFontColor": "#333",
        "tableAlign": "center"
      },
      layouts: '',


    };
  },
  created() {
    this.init();
    this.contentStyleChange()
  },
  mounted() {
    this.getDataList();
  },
  filters: {
    htmlfilter: function (val) {
      return val.replace(/<[^>]*>/g).replace(/undefined/g, '');
    }
  },
  components: {
    AddOrUpdate,
  },
  methods: {
    /*上传文件组方法*/
    handleRemove(file, fileList) {
      console.log(file, fileList);
    },
    handlePreview(file) {
      console.log(file);
    },
    handleExceed(files, fileList) {
      this.$message.warning(`当前限制选择 3 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
    },
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`);
    },

    customHttpRequest({ file, onSuccess, onError, onProgress }) {
      // 创建 FormData 对象
      const formData = new FormData();
      formData.append('file', file); // 将文件添加到表单数据中

      // 使用 this.$http 发送请求
      this.$http({
        url: 'admin/student/import-students', // 后端接口地址
        method: 'post',
        data: formData, // 使用 FormData 传输文件
        headers: {
          'Content-Type': 'multipart/form-data', // 确保以 multipart/form-data 发送
          'token':`${this.$storage.get('Token')}`
        },
        onUploadProgress: event => {
          // 计算上传进度百分比
          let percent = Math.round((event.loaded * 100) / event.total);
          onProgress({ percent }); // 调用进度回调函数
        }
      }).then(({ data }) => {
            // 检查响应数据，判断是否上传成功
            if (data && data.code === 0) {
              onSuccess(data); // 调用成功回调
              this.getDataList()
            } else {
              this.$message.error(data.msg); // 显示错误信息
              onError(data); // 调用失败回调
            }
          })
          .catch(error => {
            // 捕获请求失败的情况
            onError(error); // 调用失败回调
            console.error(error); // 打印错误信息
          });
    },
    /*组件设计方法*/
    contentStyleChange() {
      this.contentSearchStyleChange()
      this.contentBtnAdAllStyleChange()
      this.contentSearchBtnStyleChange()
      this.contentPageStyleChange()
    },
    contentSearchStyleChange() {
      this.$nextTick(() => {
        document.querySelectorAll('.form-content .slt .el-input__inner').forEach(el => {
          let textAlign = 'left'
          if (this.contents.inputFontPosition == 2) textAlign = 'center'
          if (this.contents.inputFontPosition == 3) textAlign = 'right'
          el.style.textAlign = textAlign
          el.style.height = this.contents.inputHeight
          el.style.lineHeight = this.contents.inputHeight
          el.style.color = this.contents.inputFontColor
          el.style.fontSize = this.contents.inputFontSize
          el.style.borderWidth = this.contents.inputBorderWidth
          el.style.borderStyle = this.contents.inputBorderStyle
          el.style.borderColor = this.contents.inputBorderColor
          el.style.borderRadius = this.contents.inputBorderRadius
          el.style.backgroundColor = this.contents.inputBgColor
        })
        if (this.contents.inputTitle) {
          document.querySelectorAll('.form-content .slt .el-form-item__label').forEach(el => {
            el.style.color = this.contents.inputTitleColor
            el.style.fontSize = this.contents.inputTitleSize
            el.style.lineHeight = this.contents.inputHeight
          })
        }
        setTimeout(() => {
          document.querySelectorAll('.form-content .slt .el-input__prefix').forEach(el => {
            el.style.color = this.contents.inputIconColor
            el.style.lineHeight = this.contents.inputHeight
          })
          document.querySelectorAll('.form-content .slt .el-input__suffix').forEach(el => {
            el.style.color = this.contents.inputIconColor
            el.style.lineHeight = this.contents.inputHeight
          })
          document.querySelectorAll('.form-content .slt .el-input__icon').forEach(el => {
            el.style.lineHeight = this.contents.inputHeight
          })
        }, 10)

      })
    },
    // 搜索按钮
    contentSearchBtnStyleChange() {
      this.$nextTick(() => {
        document.querySelectorAll('.form-content .slt .el-button--success').forEach(el => {
          el.style.height = this.contents.searchBtnHeight
          el.style.color = this.contents.searchBtnFontColor
          el.style.fontSize = this.contents.searchBtnFontSize
          el.style.borderWidth = this.contents.searchBtnBorderWidth
          el.style.borderStyle = this.contents.searchBtnBorderStyle
          el.style.borderColor = this.contents.searchBtnBorderColor
          el.style.borderRadius = this.contents.searchBtnBorderRadius
          el.style.backgroundColor = this.contents.searchBtnBgColor
        })
      })
    },
    // 新增、批量删除
    contentBtnAdAllStyleChange() {
      this.$nextTick(() => {
        document.querySelectorAll('.form-content .ad .el-button--success').forEach(el => {
          el.style.height = this.contents.btnAdAllHeight
          el.style.color = this.contents.btnAdAllAddFontColor
          el.style.fontSize = this.contents.btnAdAllFontSize
          el.style.borderWidth = this.contents.btnAdAllBorderWidth
          el.style.borderStyle = this.contents.btnAdAllBorderStyle
          el.style.borderColor = this.contents.btnAdAllBorderColor
          el.style.borderRadius = this.contents.btnAdAllBorderRadius
          el.style.backgroundColor = this.contents.btnAdAllAddBgColor
        })
        document.querySelectorAll('.form-content .ad .el-button--danger').forEach(el => {
          el.style.height = this.contents.btnAdAllHeight
          el.style.color = this.contents.btnAdAllDelFontColor
          el.style.fontSize = this.contents.btnAdAllFontSize
          el.style.borderWidth = this.contents.btnAdAllBorderWidth
          el.style.borderStyle = this.contents.btnAdAllBorderStyle
          el.style.borderColor = this.contents.btnAdAllBorderColor
          el.style.borderRadius = this.contents.btnAdAllBorderRadius
          el.style.backgroundColor = this.contents.btnAdAllDelBgColor
        })
        document.querySelectorAll('.form-content .ad .el-button--warning').forEach(el => {
          el.style.height = this.contents.btnAdAllHeight
          el.style.color = this.contents.btnAdAllWarnFontColor
          el.style.fontSize = this.contents.btnAdAllFontSize
          el.style.borderWidth = this.contents.btnAdAllBorderWidth
          el.style.borderStyle = this.contents.btnAdAllBorderStyle
          el.style.borderColor = this.contents.btnAdAllBorderColor
          el.style.borderRadius = this.contents.btnAdAllBorderRadius
          el.style.backgroundColor = this.contents.btnAdAllWarnBgColor
        })
      })
    },
    // 表格
    rowStyle({row, rowIndex}) {
      if (rowIndex % 2 == 1) {
        if (this.contents.tableStripe) {
          return {color: this.contents.tableStripeFontColor}
        }
      } else {
        return ''
      }
    },
    cellStyle({row, rowIndex}) {
      if (rowIndex % 2 == 1) {
        if (this.contents.tableStripe) {
          return {backgroundColor: this.contents.tableStripeBgColor}
        }
      } else {
        return ''
      }
    },
    headerRowStyle({row, rowIndex}) {
      return {color: this.contents.tableHeaderFontColor}
    },
    headerCellStyle({row, rowIndex}) {
      return {backgroundColor: this.contents.tableHeaderBgColor}
    },
    // 表格按钮

    // 分页
    contentPageStyleChange() {
      let arr = []

      if (this.contents.pageTotal) arr.push('total')
      if (this.contents.pageSizes) arr.push('sizes')
      if (this.contents.pagePrevNext) {
        arr.push('prev')
        if (this.contents.pagePager) arr.push('pager')
        arr.push('next')
      }
      if (this.contents.pageJumper) arr.push('jumper')
      this.layouts = arr.join()
      this.contents.pageEachNum = 10
    },

    init() {
      this.genderOptions = "男,女".split(',')
    },
    search() {
      this.pageIndex = 1;
      this.getDataList();
    },
    // 获取数据列表
    getDataList() {
      this.dataListLoading = true;
      let params = {
        current: this.pageIndex,
        gender: "",
        id: 0,
        pageSize: this.pageSize,
        sortField: "",
        sortOrder: "",
        studentaccount: "",
        studentcollege: "",
        studentname: "",
        unionid: "",
      }
      if (this.searchForm.studentaccount !== '' && this.searchForm.studentaccount !== undefined) {
        params['studentaccount'] = this.searchForm.studentaccount
      }
      if (this.searchForm.studentname !== '' && this.searchForm.studentname !== undefined) {
        params['studentname'] = this.searchForm.studentname
      }
      if (this.searchForm.gender !== '' && this.searchForm.gender !== undefined) {
        params['gender'] = this.searchForm.gender
      }
      this.$http({
        url: "/admin/student/list/page",
        method: "post",
        data: params
      }).then(({data}) => {
        if (data && data.code === 0) {
          this.dataList = data.data.records;
          this.totalPage = Number(data.data.total);
        } else {
          this.dataList = [];
          this.totalPage = 0;
        }
        this.dataListLoading = false;
      });
    },
    // 每页数
    sizeChangeHandle(val) {
      this.pageSize = val;
      this.pageIndex = 1;
      this.getDataList();
    },
    // 当前页
    currentChangeHandle(val) {
      this.pageIndex = val;
      this.getDataList();
    },
    // 多选
    selectionChangeHandler(val) {
      this.dataListSelections = val;
    },
    //索引
    indexMethod(index) {
      return (Number(this.pageIndex) - 1) * Number(this.pageSize) + index + 1;
    },
    // 添加/修改
    addOrUpdateHandler(id, type) {
      this.showFlag = false;
      this.addOrUpdateFlag = true;
      this.crossAddOrUpdateFlag = false;
      if (type !== 'info') {
        type = 'else';
      }
      this.$nextTick(() => {
        if (this.$refs.addOrUpdate && typeof this.$refs.addOrUpdate.init === 'function') {
          this.$refs.addOrUpdate.init(id, type);
        } else {
          console.warn('addOrUpdate reference is not available');
        }
      });

    },
    // 查看评论
    // 下载
    download(file) {
      window.open(`${file}`)
    },
    // 删除
    deleteHandler(id) {
      let ids = id
          ? [{ id: Number(id) }]
          : this.dataListSelections.map(item => {
            return { id: Number(item.id) };
          });
      console.log(ids)
      this.$confirm(`确定进行[${id ? "删除" : "批量删除"}]操作?（危险操作，该操作会造成不可逆删除）`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        this.$http({
          url: "admin/student/delete",
          method: "post",
          data: ids
        }).then(({data}) => {
          if (data && data.code === 0) {
            this.$message({
              message: "操作成功",
              type: "success",
              duration: 1500,
              onClose: () => {
                this.search();
              }
            });
          } else {
            this.$message.error(data.msg);
          }
        });
      }).catch(error => {
        this.$message.info("操作已取消")
      });
    },
  }

};
</script>
<style lang="scss" scoped>
.slt {
  margin: 0 !important;
  display: flex;
}

.ad {
  margin: 0 !important;
  display: flex;
}

.pages {
  & /deep/ el-pagination__sizes {
    & /deep/ el-input__inner {
      height: 22px;
      line-height: 22px;
    }
  }
}


.el-button + .el-button {
  margin: 0;
}

.tables {
  & /deep/ .el-button--success {
    height: 40px;
    color: #333;
    font-size: 14px;
    border-width: 1px;
    border-style: solid;
    border-color: #DCDFE6;
    border-radius: 5px;
    background-color: rgba(173, 241, 242, 1);
  }

  & /deep/ .el-button--primary {
    height: 40px;
    color: #333;
    font-size: 14px;
    border-width: 1px;
    border-style: solid;
    border-color: #DCDFE6;
    border-radius: 5px;
    background-color: rgba(202, 235, 202, 1);
  }

  & /deep/ .el-button--danger {
    height: 40px;
    color: #333;
    font-size: 14px;
    border-width: 1px;
    border-style: solid;
    border-color: #DCDFE6;
    border-radius: 5px;
    background-color: rgba(214, 186, 232, 1);
  }

  & /deep/ .el-button {
    margin: 4px;
  }
}

</style>
